#include "Mutex.hpp"
#include<mutex>
#include<string>
#include<unistd.h>

using namespace MutexModule;
int ticket = 1000;

class ThreadData
{
public:
    std::string _name;
    Mutex* _lock;

    ThreadData(std::string name,Mutex* lock)
    :_name(name),_lock(lock){}

    ~ThreadData(){}
};

void* route(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    while(1)
    {
        td->_lock->Lock();
        if(ticket > 0)
        {
            usleep(1000);
            std::cout<<td->_name<<"开始抢票:"<<ticket<<std::endl;
            ticket--;
            td->_lock->Unlock();
        }
        else
        {
            td->_lock->Unlock();
            break;
        }
    }
    return nullptr;
}

int main()
{
    Mutex mutex;
    pthread_t t1,t2,t3,t4;
    ThreadData* td1 = new ThreadData("thread-1",&mutex);
    ThreadData* td2 = new ThreadData("thread-2",&mutex);
    ThreadData* td3 = new ThreadData("thread-3",&mutex);
    ThreadData* td4 = new ThreadData("thread-4",&mutex);

    pthread_create(&t1,nullptr,route,td1);
    pthread_create(&t2,nullptr,route,td2);
    pthread_create(&t3,nullptr,route,td3);
    pthread_create(&t4,nullptr,route,td4);

    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);
    pthread_join(t4,nullptr);

    return 0;
}